<?php

namespace App\Http\Controllers\Api;

use App\Coupon;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Merchant\CouponUseController;
use App\Store;
use App\User;
use App\UserCoupon;
use Carbon\Carbon;
use EasyWeChatComposer\EasyWeChat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    public function login(Request $request)
    {
//                $user=User::find(1);
//        $token=auth('api')->login($user);
//        return $token;
//        return $this->respondWithToken($token);
        $minigram = app('wechat.mini_program');
        $info = $minigram->auth->session($request->get('code'));
        $store_id=$request->get('store_id');
        $coupon_arr=[];
        if ($store_id){
            $store=Store::find($store_id);
            $coupons=$store['coupons'];
            if ($coupons){
                $coupon_arr=explode(",",$coupons);
            }

        }
        Log::info('store_id',['store_id']);
        $is_new=0;
        if ($info) {
            $user_info = $this->decryptData($info['session_key'], $request->get('encryptedData'), $request->get('iv'));
            if ($user_info) {
                $user = User::where('openid', $user_info['openId'])->first();
                if (!$user) {
                    $user_data = [
                        'openid' => $user_info['openId'],
                        'avatar' => $user_info['avatarUrl'],
                        'country' => $user_info['country'],
                        'province' => $user_info['province'],
                        'city' => $user_info['city'],
                        'area' => isset($user_info['area']) ? $user_info['area'] : '',
                        'nickname' => $user_info['nickName'],
                        'gender' => $user_info['gender'],
                        'store_id'=>$store_id,
                        'parent_id'=>$request->get('parent_id')
                    ];
                    $user = User::create($user_data);
                    $coupon=Coupon::find(1);
                    $user_coupon=[
                        'uid'=>$user->id,
                        "coupon_id"=>$coupon->id,
                        "price"=>$coupon->price,
                        "fill_money"=>$coupon->fill_money,
                        "exp_time"=>Carbon::now()->addDays($coupon->exp_day),
                        "status"=>0,
                        "bind_goods"=>[],
                        "title"=>$coupon->title
                    ];
                    UserCoupon::create($user_coupon);
                    if ($coupon_arr){
                        $coupons_data=Coupon::whereIn('id',$coupon_arr)->get();
                        foreach ($coupons_data as $key=>$v){
                            $user_coupon1=[
                                'uid'=>$user->id,
                                "coupon_id"=>$v['id'],
                                "price"=>$v['price'],
                                "fill_money"=>$v['fill_money'],
                                "exp_time"=>Carbon::now()->addDays($v['exp_day']),
                                "status"=>0,
                                "bind_goods"=>[],
                                "title"=>$v['title']
                            ];
                            UserCoupon::create($user_coupon1);
                        }
                    }
                    $is_new=1;
                }else{
                    $unused_arr=[];
                    if ($coupon_arr){
                        foreach ($coupon_arr as $value){
                            $unused=UserCoupon::where('status',0)->where('coupon_id',$value)->where("store_id",$store_id)->where('uid',$user->id)->first();
                            if (!$unused){
                                array_push($unused_arr,$value);
                            }
                        }
                        foreach ($unused_arr as $v){
                            $coupon=Coupon::find($v);
                            $user_coupon=[
                                'uid'=>$user->id,
                                "coupon_id"=>$coupon->id,
                                "price"=>$coupon->price,
                                "fill_money"=>$coupon->fill_money,
                                "exp_time"=>Carbon::now()->addDays($coupon->exp_day),
                                "status"=>0,
                                "bind_goods"=>[],
                                "title"=>$coupon->title,
                                "store_id"=>$store_id
                            ];
                            UserCoupon::create($user_coupon);
                        }
                    }
                }
                $token = auth('api')->login($user);
                return $this->respondWithToken($token,$info['session_key'],$is_new);
            }

        }

    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token,$session_key,$is_new=0)
    {
        return response()->json([
            'code' => 200,
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user'=>auth('api')->user(),
            'session_key'=>$session_key,
            'is_new'=>$is_new,
            'api_version'=>config('app.api_version').date('Ymd')
        ]);
    }

    /*
 *  微信解密数据
 *
 * */
    /**
     * @param $session_key
     * @param $encryptedData
     * @param $iv
     * @return bool|mixed
     */
    public function decryptData($session_key, $encryptedData, $iv)
    {
        if (strlen($session_key) != 24) {
            return false;
        }
        $aesKey = base64_decode($session_key);
        if (strlen($iv) != 24) {
            return false;
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result, 1);
        if ($dataObj == NULL) {
            return false;
        }
        if ($dataObj['watermark']['appid'] != config("wechat.mini_program.default.app_id")) {
            return false;
        }
        return $dataObj;
    }
    public function getPhoneNumber(Request $request)
    {
          $minigram = app('wechat.mini_program');

            $user_info = $minigram->encryptor->decryptData($request->get('session_key'),$request->get('iv'),$request->get('encryptedData'));
            if ($user_info) {
                $openid=$request->get('openid');
                User::where('openid',$openid)->update(['phone'=>$user_info['phoneNumber']]);
               return response()->json(['code'=>200,'message'=>"获取成功"]);
            }else{
                return response()->json(['code'=>500,'message'=>"获取失败"]);

            }
    }
}
